const path = require('path');
const glob = require('glob');
const base = require('./webpack.base.js');
const { smart } = require('webpack-merge');
const PurifyCssWebpack = require('purifycss-webpack');//css tree-shaking删除项目中没有用到的css
const CopyWebpackPlugin = require('copy-webpack-plugin');//拷贝资源
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");//压缩js
const CleanWebpackPlugin = require('clean-webpack-plugin');//清空打包文件
const MiniCssExtractPlugin = require('mini-css-extract-plugin');//单独提取打包css
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");//优化压缩css

const pathResolve = (targetPath) => path.resolve(__dirname, targetPath);

module.exports = smart(base, {
  mode: 'production',//生产模式
  devtool: 'source-map',//用来检测代码bug
  output: {
    filename: 'js/[name]-[chunkhash:7].js',
    chunkFilename: 'js/[name]-[chunkhash:7].js'
  },
  plugins: [
    new CleanWebpackPlugin(['dist']),//清空打包文件夹
    new PurifyCssWebpack({//压缩js
      paths: glob.sync(pathResolve('src/*.html'))
    }),
    new CopyWebpackPlugin([{//拷贝静态资源
      from: pathResolve('src/assets'),
      to: pathResolve('dist/assets')
    }]),
    new MiniCssExtractPlugin({//单独提取css打包
      filename: 'css/[name]-[contenthash:7].css'
    })
  ],
  optimization: {
    runtimeChunk: {
      name: 'manifest'
    },
    splitChunks: {//拆分js
      cacheGroups: {
        vendor: {
          chunks: "all",
          test: /[\\/]node_modules[\\/]/,
          name: "vendor",
          minChunks: 1,
          maxInitialRequests: 5,
          minSize: 0,
          priority: 100
        }
      }
    },
    minimizer: [
      new OptimizeCSSAssetsPlugin({
        assetNameRegExp: /\.optimize\.css$/g,
        cssProcessor: require('cssnano'),
        cssProcessorOptions: { safe: true, discardComments: { removeAll: true } },
        canPrint: true
      }),
      new UglifyJsPlugin({
        cache: true,
        parallel: true,
        sourceMap: true
      }),
    ]
  }
});